<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getConsultOrderPre, createConsultOrder } from '@/api/consult'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import { getPatientDetail } from '@/api/user'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showFailToast } from 'vant'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()
const router = useRouter()
// 1. 获取支付信息
const payInfo = ref({} as ConsultOrderPreData)
const getPayInfo = async () => {
  try {
    const data = await getConsultOrderPre({
      type: store.consult.type, // 问诊类型：极速问诊
      illnessType: store.consult.illnessType // 问诊级别：普通 ｜ 三甲
    })
    console.log('支付信息：', data)
    payInfo.value = data
  } catch (error) {
    showFailToast('缺少参数，请重新挂号！')
    router.push('/home')
  }
}
// 2. 获取挂号患者信息
const patientInfo = ref({} as Patient)
const getPatient = async () => {
  const data = await getPatientDetail(store.consult.patientId!)
  console.log('患者信息：', data)
  patientInfo.value = data
}
onMounted(() => {
  getPayInfo()
  getPatient()
})
// 3. 打开选择支付方式的抽屉
const show = ref(false)
// // 支付方式: 0 微信支付 ｜ 1 支付宝支付
// const paymentMethod = ref<0 | 1>()
// 是否同意支付协议
const isAgree = ref(false)
// 订单ID
const orderId = ref('')
const openPayType = async () => {
  if (!isAgree.value) return showFailToast('请同意支付协议！')
  // 打开支付方式选择弹层
  show.value = true
  // 1. 创建订单
  const data = await createConsultOrder(store.consult)
  // 2. 存储订单ID
  orderId.value = data.id
  // 3. 清空之前记录到pinia到数据=》购物车中商品创建订单后，需要删除
  // store.clear()
}
// 通过onBeforeRouteLeave钩子函数：返回false阻止页面跳转
onBeforeRouteLeave(() => {
  // 已经创建订单了，就不能回到上一步
  if (orderId.value) return false
})
const onClose = async () => {
  // 给用户提示
  try {
    await showConfirmDialog({
      title: '提示',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付',
      // 读取全局原生css变量
      confirmButtonColor: 'var(--cp-primary)',
      closeOnPopstate: false
    })
    // 继续支付
    console.log('继续支付')
    return false
  } catch (error) {
    console.log('仍要关闭')
    // 1. 把订单ID修改为空=>解除页面跳转阻止
    orderId.value = ''
    // 2. 跳转订单列表
    router.push('/user/consult')
    return true
  }
}
// // 支付订单
// const payOrder = async () => {
//   // 1. 判断是否选择支付方式
//   if (paymentMethod.value === undefined) return showFailToast('请选择支付方式')
//   showLoadingToast('开始支付...')
//   // 2. 获取支付地址
//   const { data } = await getConsultOrderPayUrl({
//     paymentMethod: paymentMethod.value,
//     orderId: orderId.value,
//     // 回跳地址=》将来支付成功，回跳地址
//     payCallback: 'http://localhost:5173/room'
//     // 说明：如果路由模式是hash,地址需要带#号，例如：http://localhost:5173/#/room
//   })
//   // 3. 跳转支付
//   window.location.href = data.payUrl
// }
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 1. 支付信息 -->
    <div class="pay-info">
      <!-- 原价：payInfo.payment -->
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />

      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 2. 患者信息  -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 3. 打开支付弹层并创建问诊订单 -->
    <van-submit-bar
      @click="openPayType"
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
    />

    <!-- 支付弹层 -->
    <cp-pay-sheet
      v-model:show="show"
      :order-id="orderId"
      :actualPayment="payInfo.actualPayment"
      :onClose="onClose"
    />
    <!-- <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :before-close="onClose"
      :closeable="false"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button @click="payOrder" type="primary" round block>立即支付</van-button>
        </div>
      </div>
    </van-action-sheet> -->
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
}
</style>
